package com.qianchang.microfinance.setting;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.qianchang.microfinance.R;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.login.ForgetActivityOne;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.MD5Util;
import com.dm.library.utils.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.setting.PasswordManagerActivity.HAS_TRAD_PWD;


/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: 初始设置/修改  支付密码   注意这里只是初始设置支付密码，忘记支付密码后的修改不在这
 * 修 改 人: zhoulai
 * 修改时间: 2017/6/30 16:23
 */


public class SettingTradPasswordActivity extends BaseActivity implements TextWatcher {


    @BindView(R.id.et_input_set_tradpwd)
    EditText etInputSetTradpwd;
    @BindView(R.id.iv_set_tradpwd_visible)
    CheckBox ivSetTradpwdVisible;
    @BindView(R.id.et_input_pre_tradpwd)
    EditText etInputPreTradpwd;
    @BindView(R.id.iv_pre_tradpwd_visible)
    CheckBox ivPreTradpwdVisible;
    @BindView(R.id.ll_pre_tradpwd)
    LinearLayout llPreTradpwd;
    @BindView(R.id.et_input_new_tradpwd)
    EditText etInputNewTradpwd;
    @BindView(R.id.iv_newpwd_visible)
    CheckBox ivNewpwdVisible;
    @BindView(R.id.ll_new_tradpwd)
    LinearLayout llNewTradpwd;
    @BindView(R.id.ll_update_tradpwd)
    LinearLayout llUpdateTradpwd;
    @BindView(R.id.btn_sure)
    Button btnSure;
    @BindView(R.id.ll_forget_pwd)
    LinearLayout llForgetPwd;
    @BindView(R.id.ll_set_tradpwd)
    LinearLayout llSetTradpwd;
    private boolean hasTradPwd;// true 有支付密码（修改）  ;  false没有支付密码（初始设置）
    private static final String TAG = "SettingTradPasswordActivity";
    public static final String IS_TRAD_PWD = "isTradPwd";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password_trad);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    protected void initData() {
        super.initData();

        //查询用户信息，判断是否有支付密码
        hasTradPwd = getIntent().getBooleanExtra(HAS_TRAD_PWD, false);
        finishView();

        ivNewpwdVisible.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int length = etInputNewTradpwd.getText().length();
                if (isChecked) {
                    etInputNewTradpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etInputNewTradpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                etInputNewTradpwd.setSelection(length);
            }
        });

        ivPreTradpwdVisible.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int length = etInputPreTradpwd.getText().length();
                if (isChecked) {
                    etInputPreTradpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etInputPreTradpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                etInputPreTradpwd.setSelection(length);
            }
        });

        ivSetTradpwdVisible.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int length = etInputSetTradpwd.getText().length();
                if (isChecked) {
                    etInputSetTradpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etInputSetTradpwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                etInputSetTradpwd.setSelection(length);
            }
        });
    }

    private void finishView() {
        if (!hasTradPwd) {//初始设置
            setTitleName(getString(R.string.title_set_transaction_password));
            llUpdateTradpwd.setVisibility(View.GONE);
            llForgetPwd.setVisibility(View.GONE);
            llSetTradpwd.setVisibility(View.VISIBLE);
        } else {//修改密码
            llSetTradpwd.setVisibility(View.GONE);
            llUpdateTradpwd.setVisibility(View.VISIBLE);
            llForgetPwd.setVisibility(View.VISIBLE);
            setTitleName(getString(R.string.title_modify_transaction_password));
        }
    }

    @OnClick({R.id.btn_sure, R.id.ll_forget_pwd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_sure:
                if (!hasTradPwd) {
                    //初始设置支付密码
                    setTradPWd();
                } else {
                    //修改支付密码
                    updateTradPwd();
                }
                break;
            case R.id.ll_forget_pwd:
                Intent intent = new Intent(SettingTradPasswordActivity.this, ForgetActivityOne.class);
                intent.putExtra(SettingTradPasswordActivity.IS_TRAD_PWD, true);
                startActivity(intent);
                break;
        }
    }


    /**
     * 初始设置支付密码
     */
    private void setTradPWd() {
        String tradPwd = etInputSetTradpwd.getText().toString().trim();
        if (!FormatUtil.isValidTradPwd(tradPwd)) {
            ToastUtil.getInstant().show(SettingTradPasswordActivity.this, getString(R.string.msg_pwd_not_ok));
            return;
        }
        show();
        HttpParams params = new HttpParams();
        params.put("transactionPwd", MD5Util.string2MD5(
                tradPwd + ConstantAppInfo.Password.PASSWORD_SUFFIX));
        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.INSERT_TRAN_PWD, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                DMLog.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    Intent intent = new Intent(SettingTradPasswordActivity.this, PasswordManagerActivity.class);
                    intent.putExtra(HAS_TRAD_PWD, true);
                    setResult(PasswordManagerActivity.REQUEST_OK, intent);
                }else{
                    ToastUtil.getInstant().show(SettingTradPasswordActivity.this, response.getDescription());
                }
                SettingTradPasswordActivity.this.finish();
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(SettingTradPasswordActivity.this, msg);// getString(R.string.msg_indentity_code_send_fail));
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(SettingTradPasswordActivity.this, msg);
            }
        });
    }

    /**
     * 修改支付密码
     */
    private void updateTradPwd() {
        String prePwd = etInputPreTradpwd.getText().toString().trim();
        String pwd = etInputNewTradpwd.getText().toString().trim();

        if (!FormatUtil.isValidTradPwd(prePwd)) {
            ToastUtil.getInstant().show(SettingTradPasswordActivity.this, getString(R.string.msg_pwd_not_ok));
            return;
        }

        if (!FormatUtil.isValidTradPwd(pwd)) {
            ToastUtil.getInstant().show(SettingTradPasswordActivity.this, getString(R.string.msg_pwd_not_ok));
            return;
        }
        show();
        HttpParams params = new HttpParams();
        params.put("oldTransactionPwd", MD5Util.string2MD5(
                prePwd + ConstantAppInfo.Password.PASSWORD_SUFFIX));

        params.put("newTransactionPwd", MD5Util.string2MD5(
                pwd + ConstantAppInfo.Password.PASSWORD_SUFFIX));

        params.put("type", "1");        /**1表示修改,2表示找回*/

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.UPDATE_FORGET_TRAN_PWD, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                DMLog.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    SettingTradPasswordActivity.this.finish();
                }else{
                    ToastUtil.getInstant().show(SettingTradPasswordActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(SettingTradPasswordActivity.this, msg);// getString(R.string.msg_indentity_code_send_fail));
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(SettingTradPasswordActivity.this, msg);
            }

        });
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    /**
     * 文本变化之后检测
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        checkButtonEnable();
    }

    /**
     * 检测按钮是否激活
     */
    private void checkButtonEnable() {
  /*      String s_1 = etInputTradpwd.getText().toString();
        String s_0 = etInputTradpwdsure.getText().toString();

        String s_2 = etInputPrePwd.getText().toString();
        String s_3 = etInputPwd.getText().toString();
        String s_4 = etInputPwdSure.getText().toString();

        if (!hasTradPwd) {
            if (FormatUtil.isVerificatCode(s_1) && FormatUtil.isVerificatCode(s_0)) {
                btnSure.setEnabled(true);
            } else {
                btnSure.setEnabled(false);
            }
        } else {
            if (FormatUtil.isVerificatCode(s_2) && FormatUtil.isVerificatCode(s_3) && FormatUtil.isVerificatCode(s_4)) {
                btnSure.setEnabled(true);
            } else {
                btnSure.setEnabled(false);
            }
        }*/

    }

}
